package com.example.interesting.distributed.log.realize.resttemplate;

import com.example.interesting.distributed.log.realize.util.LogTraceInit;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.util.Map;

/**
 * @Description: restTemplate调用方式的日志拦截器
 * @Author: fyw
 * @Date: 2024/4/4 17:04
 * @History
 */
public class LogRestTemplateInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        //获取mdc日志扩展信息，并替换服务名
        Map<String, String> stringStringMap = LogTraceInit.replaceServiceName();
        //添加到请求头传递到下面的服务
        HttpHeaders headers = request.getHeaders();
        stringStringMap.forEach(headers::add);
        return execution.execute(request, body);
    }

}
